package sc.nio;

import java.util.ArrayList;
import java.util.List;

public class NioConnection
{
	// The NioClient this reader is registered with
	private NioClient nioclient;
	
	// Queue of received data
	private List<byte[]> pending = new ArrayList<byte[]>();
	
	/**
	 * Creates an instance of NioReader.
	 */
	public NioConnection(NioClient nioclient)
	{
		this.nioclient = nioclient;
	}

	/**
	 * Writes a sequence of bytes to the connection.
	 * 
	 * @param buffer
	 * 			The bytes to write
	 */
	public void send(byte[] buffer)
	{
		this.nioclient.send(buffer);
	}
	
	/**
	 * Queues data for reading.
	 * 
	 * @param buffer
	 * 			The bytes received
	 */
	public void receive(byte[] buffer)
	{
		synchronized (pending)
		{
			pending.add(buffer);
			pending.notify();
		}
	}
	
	/**
	 * Reads a sequence of bytes from the connection.
	 *  
	 * @return The bytes waiting to be read; else null if none available
	 */
	public byte[] read()
	{
		// If data is available, return the first off the queue
		synchronized (pending)
		{
			if (!pending.isEmpty())
				return pending.remove(0);
		}
		
		return null;
	}
}
